<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="部门名" prop="deptId">
        <el-input v-model="formData.deptName" placeholder="请输入部门id" :disabled="true" />
      </el-form-item>
      <!-- <el-form-item label="科室采购单编号" prop="orderId">
        <el-input v-model="formData.orderId" placeholder="请输入科室采购单编号" />
      </el-form-item> -->
      <!-- <el-form-item label="仓库编号" prop="warehouseId">
        <el-input v-model="formData.warehouseId" placeholder="请输入仓库编号" />
      </el-form-item> -->
      <!-- <el-form-item label="整合单编号" prop="integrateId">
        <el-input v-model="formData.integrateId" placeholder="请输入整合单编号" />
      </el-form-item> -->
      <el-form-item label="备注" prop="remark">
        <el-input v-model="formData.remark" placeholder="请输入备注"  :disabled="true" />
      </el-form-item>
      <!-- <el-form-item label="状态" prop="status">
        <el-radio-group v-model="formData.status">
          <el-radio
            v-for="dict in getIntDictOptions(DICT_TYPE.PURCHASE_APPLY_STATUS)"
            :key="dict.value"
            :label="dict.value"
          
          >
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item> -->
      <!-- <el-form-item label="流程实例的编号" prop="processInstanceId">
        <el-input v-model="formData.processInstanceId" placeholder="请输入流程实例的编号" />
      </el-form-item> -->
    </el-form>
    <!-- 子表的表单 -->
    <el-tabs v-model="subTabsName">
      <el-tab-pane label="ERP 科室采购申请项" name="depPurchaseItem">
        <DepPurchaseItemForm ref="depPurchaseItemFormRef" :order-id="formData.id" />
      </el-tab-pane>
    </el-tabs>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { getIntDictOptions, DICT_TYPE } from '@/utils/dict'
import { DepPurchaseApi, DepPurchaseVO } from '@/api/erp/deppurchase'
import { DepPurchaseItemApi, DepPurchaseItemVO } from '@/api/erp/deppurchaseitem'
import { PriStockApi, PriStockVO } from '@/api/erp/pristock'
import { PriAccountApi, PriAccountVO } from '@/api/erp/priaccount'

import DepPurchaseItemForm from './components/DepPurchaseItemForm.vue'

/** ERP 科室采购申请单 表单 */
defineOptions({ name: 'DepPurchaseForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  deptId: undefined,
  deptName: undefined,
  orderId: undefined,
  warehouseId: undefined,
  integrateId: undefined,
  remark: undefined,
  status: undefined,
  processInstanceId: undefined,
})
const updatePriStockdata = ref({
  productId: undefined,
  count: undefined
})
const updatPriAccountdata = ref({
affairs: '出库',
productName: undefined,
productId: undefined,
productUnitId: undefined,
productStandards: undefined,
productPrice : undefined,
count : undefined , 
   
})
const formRules = reactive({
  orderId: [{ required: true, message: '科室采购单编号不能为空', trigger: 'blur' }],
  status: [{ required: true, message: '状态不能为空', trigger: 'blur' }],
})
const formRef = ref() // 表单 Ref

/** 子表的表单 */
const subTabsName = ref('depPurchaseItem')
const depPurchaseItemFormRef = ref()

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await DepPurchaseApi.getDepPurchase(id)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
 
 // 校验表单
 await formRef.value.validate()
 // 校验子表单
 try {
   await depPurchaseItemFormRef.value.validate()
 } catch (e) {
   subTabsName.value = 'depPurchaseItem'
   return
 }
 // 提交请求
 formLoading.value = true
 try {
   //  采购申请项
    const data = formData.value as unknown as DepPurchaseItemVO
    // console.log('子表数据11', depPurchaseItemFormRef.value.getData())
   // 处理子表中的数据
     const zidata = depPurchaseItemFormRef.value.getData();
     zidata.forEach(item => {
     if (item.nums !== null && item.countss !== null) {
      item.nums += item.countss;
     } else if (item.nums === null && item.countss !== null) {
       item.nums = item.countss;
     }
     // 如果 nums 为 null 且 count 也为 null，则不进行任何操作
     });
    //  console.log('子表数据22', zidata)
     data.depPurchaseItems = zidata
    // console.log('主表数据',data)
    let deptId: number
      const Info = JSON.parse(localStorage.getItem('user') || '{}');
      const userInfo = JSON.parse(Info.v)
      deptId = userInfo.user.deptId
      
     // 分发修改采购单数据
      DepPurchaseApi.fenfa(data)
      // 分发修改一级库以及一级库台账
      const productIdAndCountss = data.depPurchaseItems
     .filter(item => item.countss != null && item.countss !== undefined) // 过滤掉 countss 为空或 undefined 的元素
     .map(item => ({
       deptId: deptId,
       productId: item.productId,
       count: item.countss
     }));
    //  console.log(productIdAndCountss,'分发修改一级库以及一级库台账');
     if(productIdAndCountss.length > 0){ // 判断是否进行了分发操作
       PriStockApi.updatePriStockdelect(productIdAndCountss)
     }
      

   dialogVisible.value = false
   // 发送操作成功的事件
   emit('success')
 } finally {
   formLoading.value = false
 }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    deptId: undefined,
    orderId: undefined,
    warehouseId: undefined,
    integrateId: undefined,
    remark: undefined,
    status: undefined,
    processInstanceId: undefined,
  }
  formRef.value?.resetFields()
}
</script>